// Copyright (C) 2022 Huawei Device Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package utils

import (
	"crypto/sha256"
	"dist/model"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"net/http"
	"strings"
)

func GetIP(r *http.Request) (string, error) {
	ip := r.Header.Get("X-Real-IP")
	if net.ParseIP(ip) != nil {
		return ip, nil
	}
	ip = r.Header.Get("X-Forward-For")
	for _, i := range strings.Split(ip, ",") {
		if net.ParseIP(i) != nil {
			return i, nil
		}
	}
	ip, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return "", err
	}

	if net.ParseIP(ip) != nil {
		return ip, nil
	}
	return "", errors.New("no valid ip found")
}

func MapToJson(m interface{}) (string, error) {
	marshal, err := json.Marshal(m)
	if err != nil {
		return "", err
	}
	var str = string(marshal)
	return str, nil
}

func Resp(w http.ResponseWriter) func(int, string, interface{}) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "OPTIONS,POST,GET,PUT,DELETE")
	w.Header().Set("Access-Control-Max-Age", "3600")
	w.Header().Set("Access-Control-Allow-Headers", "*")
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	return func(code int, msg string, obj interface{}) {
		var data = model.ResponseData{Code: code, Msg: msg, Data: obj}
		toJson, err := MapToJson(data)
		if err != nil {
			errdata := model.ResponseData{Code: -1, Msg: err.Error()}
			errRes, _ := MapToJson(errdata)
			fmt.Fprintf(w, errRes)
		} else {
			fmt.Fprintf(w, toJson)
		}
	}
}

func Encrypt(str string) string {
	sha := sha256.New()
	sha.Write([]byte(str))
	res := sha.Sum(nil)
	resStr := hex.EncodeToString(res)
	return resStr
}

func RequestToStruct(req *http.Request, dataStruct interface{}) error {
	contentType := req.Header["Content-Type"]
	if len(contentType) > 0 {
		contentTypeName := contentType[0]
		if strings.HasPrefix(contentTypeName, "application/json") {
			decoder := json.NewDecoder(req.Body)
			decoder.Decode(&dataStruct)
			return nil
		}
	}
	Error.Printf("convert failed %v", req.Body)
	return errors.New("convert failed")
}
